package core.login;

import java.io.IOException;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import config.mm_config;
import core.net.mm_http_client;
import core.random_code.mm_random_code;
import core.reactor.mm_reactor;
import log.mm_logger;
import utils.mm_thread;

/**
 * 登陆器
 * @author dongyazhuo
 */
public class mm_login {

	private String TAG = mm_login.class.getSimpleName() + " : ";

	private String uamtk = null;

	private String user_name = null;

	private mm_http_client _mm_http_client;

	private mm_config _mm_config = null;

	private mm_random_code _mm_random_code = null;

	public mm_login(mm_reactor _mm_reactor) {
		super();
		this._mm_random_code = _mm_reactor._mm_random_code;
		this._mm_http_client = _mm_reactor._mm_http_client;
		this._mm_config = _mm_reactor._mm_config;
		TAG += _mm_config.getSet().getAccount_12306().getUser() + " : ";
	}

	public mm_http_client get_mm_http_client() {
		return _mm_http_client;
	}

	/**
	 * 登陆，读取配置文件，尝试去登陆
	 * @throws IOException
	 */
	public void login() {
		if (_mm_config.getSet().getAccount_12306().isQuery()) {
			mm_logger.i(TAG + "login_mode is query.");
			return;
		}
		// 请求抢票页面
		req_lift_ticket_init();
		req_lift_ticket_init();
		mm_logger.i(TAG + "req_lift_ticket_init ok .");
		// 晚上休眠
		check_sleep_time();
		go_login();
		mm_logger.i(TAG + "mm_login login finish !!!");
	}

	private void go_login() {
		String user = _mm_config.getSet().getAccount_12306().getUser();
		String pwd = _mm_config.getSet().getAccount_12306().getPwd();
		if (null == user || null == pwd || "".equals(user) || "".equals(pwd)) {
			mm_logger.e(TAG + "温馨提示: 用户名或者密码为空，请仔细检查");
			return;
		}
		int login_num = 1;

		do {
			// 请求生成新的验证码
			_mm_random_code.get_pass_code_new(true);
			// 登陆初始化
			loginInit();
			// 检查是否登陆
			auth();
			// 验证码校验
			if (_mm_random_code.login_code_check()) {
				// 登陆
				boolean login_reslut = baseLogin();
				if (login_reslut) {
					boolean get_user_name_reslut = get_user_name();
					mm_logger.i(TAG + "login_num :" + login_num + " result : " + login_reslut);
					if (get_user_name_reslut) {
						mm_logger.i(TAG + "user_name : " + user_name + " welcom login ok!!! ");
						return;
					}
				}
			}
			login_num++;
		} while (true);
	}

	public void req_lift_ticket_init() {
		Map<String, Object> url = _mm_config.getUrl_config().get("left_ticket_init");
		_mm_http_client.send(url, Collections.emptyMap());
	}

	/**
	 * # 防止网上启动晚上到点休眠
	 */
	public void check_sleep_time() {
		do {
			int hours = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
			// mm_logger.i(TAG + "login current hour is " + hours + " .");
			if (hours < 6) {
				mm_logger.i(TAG + "12306休息时间，本程序自动停止,明天早上六点点将自动运行");
				mm_thread.sleep(1000 * 10);
			} else {
				return;
			}
		} while (true);

	}

	private boolean baseLogin() {
		Map<String, Object> map = _mm_config.getUrl_config().get("login");
		Map<String, Object> data = new HashMap<>();
		String username = _mm_config.getSet().getAccount_12306().getUser();
		String password = _mm_config.getSet().getAccount_12306().getPwd();
		data.put("username", username);
		data.put("password", password);
		data.put("appid", "otn");
		HashMap r = (HashMap) _mm_http_client.send(map, data);
		mm_logger.i(TAG + "baseLogin http result : " + r);
		if (null != r && r.size() > 0) {
			if (r.get("result_message").equals("登录成功")) {
				auth();
				// uamtk = r.get("uamtk").toString();
				return true;
			}
		}
		return false;
	}

	private String auth() {
		Map<String, Object> map = _mm_config.getUrl_config().get("auth");
		Map<String, Object> data = new HashMap<>();
		data.put("appid", "otn");
		Object reslut = _mm_http_client.send(map, data);
		if (null != reslut) {
			HashMap r = (HashMap) reslut;
			mm_logger.i(TAG + "auth http result : " + r);
			if (null != r && r.size() > 0) {

				if (null != r.get("newapptk")) {
					uamtk = r.get("newapptk").toString();
					return uamtk;
				}
			}
		}
		return null;
	}

	private boolean get_user_name() {
		Map<String, Object> map = _mm_config.getUrl_config().get("uamauthclient");
		Map<String, Object> data = new HashMap<>();
		data.put("tk", uamtk);
		Object object = _mm_http_client.send(map, data);
		if (object != null) {
			HashMap r = (HashMap) object;
			mm_logger.i(TAG + "get_user_name http result : " + r);
			if (null != r && r.size() > 0) {
				if (0 == Integer.parseInt(r.get("result_code").toString())) {
					user_name = r.get("username").toString();
					return true;
				}
			}
		} else {
			_mm_http_client.send(map, data);
			_mm_config.getUrl_config().get("getUserInfo");
			_mm_http_client.send(map, data);
			return false;
		}
		return false;
	}

	private Object loginInit() {
		Map<String, Object> map = _mm_config.getUrl_config().get("loginInit");
		Map<String, Object> data = new HashMap<>();
		return _mm_http_client.send(map, data);
	}

}
